package vip.xiaonuo.xinmiao.modular.client.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.auth.api.SaBaseLoginUserApi;
import vip.xiaonuo.auth.core.annotation.SaClientCheckLogin;
import vip.xiaonuo.auth.core.pojo.SaBaseClientLoginUser;
import vip.xiaonuo.auth.core.util.StpClientLoginUserUtil;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.dev.api.DevConfigApi;
import vip.xiaonuo.xinmiao.modular.client.param.XmClientUpdatePasswordParam;

import javax.annotation.Resource;
import javax.validation.Valid;


@Api(tags = "用户端用户相关控制器")
@ApiSupport(author = "SNOWY_TEAM", order = 1)
@RestController
@RequestMapping("/client/c/user")
@Validated
public class XmUserController {

    @Resource(name = "clientLoginUserApi")
    private SaBaseLoginUserApi saBaseLoginUserApi;

    @ApiOperationSupport
    @ApiOperation("修改密码")
    @SaClientCheckLogin
    @PostMapping("/updatePassword")
    public CommonResult<String> updatePassword(@RequestBody @Valid XmClientUpdatePasswordParam param) {
        SaBaseClientLoginUser saBaseClientLoginUser = StpClientLoginUserUtil.getClientLoginUser();
        SaBaseClientLoginUser user = saBaseLoginUserApi.getClientUserById(saBaseClientLoginUser.getId());
        String oldPwd = CommonCryptogramUtil.doHashValue(CommonCryptogramUtil.doSm2Decrypt(param.getOldPassword()));
        if (!oldPwd.equals(user.getPassword())) {
            throw new CommonException("原密码错误!");
        }
        String newPwd = CommonCryptogramUtil.doHashValue(CommonCryptogramUtil.doSm2Decrypt(param.getNewPassword()));
        if (!newPwd.equals(user.getPassword()) && !newPwd.equals(oldPwd)) {
            saBaseLoginUserApi.updatePassword(user.getId(), newPwd);
            return CommonResult.ok();
        }
        throw new CommonException("修改失败，新密码与原密码相同!");
    }

}
